<template>
  <div class="page-wrapper">
    <div style="text-align: left; margin-bottom: 10px;">
      <span style="display: inline-block; margin-right: 10px;">选择时间:</span>
      <el-date-picker
        v-model="date"
        type="date"
        placeholder="选择日期"
        :picker-options="pickerOptions"
        format="yyyy-M-d"
        value-format="yyyy-M-d"
        size="mini"
        @change="dateChange"
      ></el-date-picker>
    </div>
    <div class="container">
      <c-box title="设备分布图" class="item1">
        <load-data-wrapper :status="status1">
          <echart-wrapper :click-handle="clickHandle" :option="option1"></echart-wrapper>
        </load-data-wrapper>
        <!-- <div id="echarts-1" class="echarts"></div> -->
      </c-box>
      <c-box title="电压器负荷曲线" class="item2">
        <load-data-wrapper :status="status2">
          <echart-wrapper :option="option2"></echart-wrapper>
        </load-data-wrapper>
        <!-- <div id="echarts-2" class="echarts"></div> -->
      </c-box>
      <c-box :title="devName + '负载率(cos实际与cos=0.95)'" class="item3">
        <load-data-wrapper :status="status3">
          <echart-wrapper :option="option3"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box :title="devName + '-综合功率损耗率-电量'" class="item4">
        <load-data-wrapper :status="status4">
          <echart-wrapper :option="option4"></echart-wrapper>
        </load-data-wrapper>
      </c-box>
      <c-box title="电费节省(元)" class="item5">
        <load-data-wrapper :status="status5">
          <echart-wrapper :option="option5"></echart-wrapper>
        </load-data-wrapper>
        <!-- <div id="echarts-5" class="echarts"></div> -->
      </c-box>
    </div>
  </div>
</template>

<script>
import { getTransDis, getRealTimePower95 } from "@/api/power";
import { getMonthDay, getLastDayOfMonth, getLastMonth } from "@/utils";
import CBox from "@/components/PageCard";
import LoadDataWrapper from "@/components/base/LoadDataWrapper";
import EchartWrapper from "@/components/EchartWrapper";
import {
  colors,
  color,
  activeColor,
  textColor,
  legend,
  grid
} from "@/utils/echarts";
const now = getLastDayOfMonth(getLastMonth(new Date()));
export default {
  name: "Switcher",
  components: {
    CBox,
    LoadDataWrapper,
    EchartWrapper
  },
  data() {
    return {
      date: now,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > new Date(now).getTime();
        }
      },
      pdfs: [],
      echarts1: null,
      echarts2: null,
      echarts3: null,
      echarts4: null,
      echarts5: null,
      selectByqs: [],
      byqData: [],
      savePower: [],
      curByq: null,

      status1: "loading",
      status2: "loading",
      status3: "loading",
      status4: "loading",
      status5: "loading",
      option1: null,
      option2: null,
      option3: null,
      option4: null,
      option5: null,
      devName: ""
    };
  },
  computed: {
    comId() {
      return this.$store.getters.comId;
    }
  },
  async mounted() {
    try {
      const data = await getTransDis(this.comId);
      if (!data || (data && data.length === 0)) {
        this.status1 = "empty";
        this.status2 = "empty";
        this.status3 = "empty";
        this.status4 = "empty";
        this.status5 = "empty";
        return this.$message.error("该公司变压器数据数据...");
      }
      this.pdfs = data;
      for (let i = 0; i < data.length; i++) {
        const d = data[i];
        if (d.transformers instanceof Array && d.transformers.length > 0) {
          this.selectByqs.push(d.id + "-" + d.transformers[0].id);
          this.curByq = d.id + "-" + d.transformers[0].id;
          this.devName = d.name + "-" + d.transformers[0].name;
          break;
        }
      }
      this.status1 = "load";
      this.setOption1();

      this.getRealTimePower95(this.selectByqs[0], this.devName).finally(() => {
        this.status2 = "load";
        this.status3 = "load";
        this.status4 = "load";
        this.setOption2();
        this.setOption3();
        this.setOption4();
      });
      this.getRealDfjs(this.selectByqs[0], this.devName).finally(() => {
        this.status5 = "load";
        this.setOption5();
      });
    } catch (e) {
      console.error(e);
      this.status1 = "error";
      this.status2 = "error";
      this.status3 = "error";
      this.status4 = "error";
      this.status5 = "error";
      // this.setOption2();
      // this.setOption3();
      // this.setOption4();
      // this.setOption5();
    }
  },
  methods: {
    setOption1() {
      const isActive = id => {
        const a = this.selectByqs.find(b => {
          const c = b.split("-");
          return c[0] === id.toString();
        });
        return !!a;
      };
      const data1 = [],
        data2 = [];
      this.pdfs.forEach(p => {
        const a = isActive(p.id);
        data1.push({
          name: p.name,
          id: p.id,
          value: p.transformers.length,
          itemStyle: {
            color: a ? activeColor : color
          }
        });
        p.transformers.forEach(t => {
          data2.push({
            pdfId: p.id,
            pdfName: p.name,
            name: t.name,
            id: t.id,
            value: 1,
            itemStyle: {
              color:
                this.selectByqs.indexOf(p.id + "-" + t.id) >= 0
                  ? activeColor
                  : color
            }
          });
        });
      });

      const option = {
        tooltip: {
          formatter: "{a} {b}"
        },
        grid: {
          bottom: 150,
          left: 100,
          right: "10%"
        },
        legend: {
          show: false,
          orient: "vertical",
          top: "middle",
          right: "5%",
          textStyle: {
            color: "#f2f2f2",
            fontSize: 14
          },
          icon: "roundRect"
        },
        series: [
          // 主要展示层的
          {
            radius: ["40%", "60%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            itemStyle: {
              normal: {
                color: color,
                borderColor: "white"
              }
            },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "配电房",
            data: data1
          },
          {
            radius: ["60%", "80%"],
            center: ["50%", "50%"],
            type: "pie",
            hoverAnimation: false,
            itemStyle: {
              normal: {
                color: color,
                borderColor: "white"
              }
            },
            label: {
              normal: {
                show: true,
                position: "inner",
                textStyle: {
                  fontSize: 12
                }
              }
            },
            name: "变压器",
            data: data2
          }
        ]
      };
      // this.echarts1.setOption(option);
      this.option1 = option;
    },
    // 电压器负荷曲线
    setOption2() {
      var timeData = [],
        data = [],
        t = this.date,
        t1 = new Date(t).getTime(),
        spt = 1000 * 60 * 15,
        len = 0;

      this.byqData.forEach(b => {
        if (this.selectByqs.indexOf(b.ids) >= 0) {
          try {
            if (len < b.data.fhqx.length) {
              len = b.data.fhqx.length;
            }
            data.push({
              type: "line",
              hoverAnimation: false,
              name: b.name,
              data: b.data.fhqx,
              smooth: true
            });
          } catch (e) {
            data.push({
              type: "line",
              hoverAnimation: false,
              name: b.name,
              smooth: true
            });
          }
        }
      });
      for (let i = 0; i < len; i++) {
        const a = new Date(t1);
        timeData.push(a.getUTCHours() + ":" + a.getMinutes());
        t1 = t1 + spt;
      }

      const option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false
          }
        },
        textStyle: {
          color: textColor
        },
        legend,
        grid,
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            axisLine: {
              onZero: true,
              lineStyle: {
                color: textColor
              }
            },
            data: timeData
          }
        ],
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            }
          }
        ],
        series: data
      };
      // this.echarts2.clear()
      // this.echarts2.setOption(option, true);
      this.option2 = option;
    },
    // 负载率(cos实际与cos=0.95)
    setOption3() {
      var timeData = [],
        data = null,
        data2 = null,
        t = this.date,
        t1 = new Date(t).getTime(),
        spt = 1000 * 60 * 15,
        lData = [],
        len = 0;

      this.byqData.forEach(b => {
        if (b.ids === this.curByq) {
          lData.push(b.name);
          let m;
          if (b.data instanceof Object) {
            if (len < b.data.peaS.length) {
              len = b.data.peaS.length;
            }
            if (len < b.data.peaP.length) {
              len = b.data.peaP.length;
            }
            m = b.data.tra[0];
          }

          data = {
            type: "bar",
            hoverAnimation: false,
            barMaxWidth: 10,
            barGap: "50%",
            name: b.name,
            data: b.data && b.data.peaP
          };
          data2 = {
            type: "bar",
            hoverAnimation: false,
            barMaxWidth: 10,
            barGap: "50%",
            barCategoryGap: "40%",
            name: b.name + "(cos=0.95)",
            data: b.data && b.data.peaS
          };
          if (m instanceof Object) {
            data.markLine = {
              data: [
                {
                  name: "经济运行区上限负载率",
                  yAxis: m.ewzHighLoadRt,
                  value: m.ewzHighLoadRt
                },
                {
                  name: "最佳经济运行区上限负载率",
                  yAxis: m.ewzHighLoadRtBest,
                  value: m.ewzHighLoadRtBest
                }
              ]
            };
            data2.markLine = {
              data: [
                {
                  name: "经济运行区下限负载率",
                  yAxis: m.ewzLowLoadRt,
                  label: { show: true }
                },
                {
                  name: "最佳经济运行区下限负载率",
                  yAxis: m.ewzLowLoadRtBest
                }
              ]
            };
          }
        }
      });
      for (let i = 0; i < len; i++) {
        const a = new Date(t1);
        timeData.push(a.getUTCHours() + ":" + a.getMinutes());
        t1 = t1 + spt;
      }

      const option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false
          }
        },
        textStyle: {
          color: textColor
        },
        legend,
        dataZoom: [
          {
            type: "slider",
            show: true,
            realtime: true,
            start: 30,
            end: 45,
            textStyle: {
              color: textColor
            }
          }
        ],
        grid: {
          ...grid,
          right: 50
        },
        xAxis: [
          {
            type: "category",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            data: timeData
          }
        ],
        yAxis: [
          {
            type: "value",
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            max: 1
          }
        ],
        series: [data, data2]
      };
      // this.echarts2.clear()
      // this.echarts3.setOption(option, true);
      this.option3 = option;
    },
    // 综合功率损耗率-电量
    setOption4() {
      var timeData = [],
        data = {
          type: "bar",
          hoverAnimation: false,
          barMaxWidth: 10,
          barCategoryGap: "50%",
          name: "电量",
          data: []
        },
        data2 = {
          type: "line",
          hoverAnimation: false,
          name: "综合功率损耗",
          data: [],
          yAxisIndex: 1
        },
        t1 = new Date(this.date).getTime(),
        spt = 1000 * 60 * 15,
        lData = [],
        len = 0;
      this.byqData.forEach(b => {
        if (b.ids === this.curByq) {
          lData.push(b.name);
          if (b.data instanceof Object) {
            if (len < b.data.peaPGvzz.length) {
              len = b.data.peaPGvzz.length;
            }
            if (len < b.data.peaGvzx.length) {
              len = b.data.peaGvzx.length;
            }
            data.data = b.data.peaPGvzz;
            data2.data = b.data.peaGvzx;
          }
        }
      });
      for (let i = 0; i < len; i++) {
        const a = new Date(t1);
        timeData.push(a.getUTCHours() + ":" + a.getMinutes());
        t1 = t1 + spt;
      }

      const option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false
          }
        },
        textStyle: {
          color: textColor
        },
        legend,
        dataZoom: [
          {
            type: "slider",
            show: true,
            realtime: true,
            start: 30,
            end: 60,
            textStyle: {
              color: textColor
            }
          }
        ],
        grid: {
          ...grid,
          top: 60
        },
        xAxis: [
          {
            type: "category",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            },
            data: timeData
          }
        ],
        yAxis: [
          {
            name: "kw.h",
            type: "value",
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: textColor
              }
            }
          },
          {
            name: "kw",
            type: "value",
            splitLine: {
              show: false
            },
            axisLine: {
              lineStyle: {
                color: textColor
              }
            }
          }
        ],
        series: [data, data2]
      };
      // this.echarts2.clear()
      // this.echarts4.setOption(option, true);
      this.option4 = option;
    },
    // 节省电费
    setOption5() {
      var xData = new Set(),
        data = [],
        lData = [],
        // saves = [],
        n = getMonthDay(this.date);

      // console.log(this.savePower);
      this.savePower.forEach(p => {
        if (this.selectByqs.indexOf(p.ids) >= 0) {
          const _data = [];
          for (let d = 1; d <= n; d++) {
            xData.add(d);
            const c = p.data.find(e => parseInt(e.dayVal) === d);
            if (c) {
              _data.push(c.valueSum);
            } else {
              _data.push(null);
            }
          }
          lData.push(p.name);
          data.push({
            type: "line",
            name: p.name,
            data: _data,
            smooth: true
          });
        }
      });

      const option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            animation: false
          }
        },
        textStyle: {
          color: textColor
        },
        legend: {
          ...legend,
          data: lData
        },
        grid,
        xAxis: [
          {
            type: "category",
            boundaryGap: false,
            axisLine: {
              onZero: true,
              lineStyle: {
                color: textColor
              }
            },
            data: Array.from(xData)
          }
        ],
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: textColor
              }
            }
          }
        ],
        series: data
      };
      // this.echarts5.setOption(option, true);
      this.option5 = option;
    },
    async clickHandle(p) {
      if (p.seriesIndex === 0) {
        return;
        // this.selectPdf(p.name);
      } else {
        await this.selectByq(
          p.data.pdfId + "-" + p.data.id,
          p.data.pdfName + "-" + p.name
        );
        this.setOption1();
        this.setOption2();
        this.setOption3();
        this.setOption4();
        this.setOption5();
      }
    },
    async getRealTimePower95(ids, name) {
      const a = this.byqData.find(f => f.name === name);
      if (a) {
        this.$set(a, "selected", !a.selected);
      } else {
        const data = await getRealTimePower95(this.comId, this.date, ids);
        this.byqData.push({
          name,
          ids,
          data: data,
          selected: true
        });
      }
    },
    async selectByq(ids, name) {
      this.curByq = ids;
      this.devName = name;
      await this.getRealTimePower95(ids, name);
      await this.getRealDfjs(ids, name);
      const index = this.selectByqs.indexOf(ids);
      if (index >= 0) {
        this.selectByqs.splice(index, 1);
        // this.selectByqs = this.selectByqs.filter(b => b !== name);
      } else {
        // this.selectByqs.length < 5 && (await this.getRealTimePower95(name));
        this.selectByqs.length < 5 && this.selectByqs.push(ids);
      }
    },
    async getRealDfjs(ids, name) {
      const a = this.savePower.find(f => f.name === name);
      if (a) {
        this.$set(a, "selected", !a.selected);
      } else {
        const t = new Date(this.date),
          [substationId, transformerId] = ids.split("-"),
          post = {
            year: t.getFullYear(),
            month: t.getMonth() + 1,
            day: t.getDate(),
            id: this.comId,
            substationId,
            transformerId
          };
        const res = await this.$axios.post("/eng/tra/realDfjs", post);
        this.savePower.push({
          name: name,
          ids: ids,
          data: res.data,
          selected: true
        });
      }
    },
    async dateChange() {
      this.byqData = [];
      this.savePower = [];
      const sqs = this.selectByqs;
      const curByq = this.curByq;
      this.selectByqs = [];
      for (let i = 0; i < sqs.length; i++) {
        const e = sqs[i];
        await this.selectByq(e);
      }
      this.curByq = curByq;

      this.setOption2();
      this.setOption3();
      this.setOption4();
      this.setOption5();
    }
  }
};
</script>

<style lang="scss" scoped>
.page-wrapper {
  flex-direction: column;
  .container {
    flex: 1;
    display: grid;
    // grid-template-columns: repeat(8, 1fr);
    // grid-template-rows: repeat(2, 1fr);
    grid-template: repeat(2, 1fr) / repeat(8, 1fr);
    grid-gap: 10px;
    .item1 {
      grid-column-start: span 2;
    }
    .item2,
    .item3 {
      grid-column-start: span 3;
    }
    .item4 {
      grid-column-start: span 3;
    }
    .item5 {
      grid-column-start: span 5;
    }
  }
}
.row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  .echarts {
    width: 100%;
    height: 100%;
  }
}
</style>
